/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.famhealing.gcm;

import static com.example.famhealing.gcm.CommonUtilities.SENDER_ID;
import static com.example.famhealing.gcm.CommonUtilities.displayMessage;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;

import com.example.famhealing.R;
import com.google.android.gcm.GCMBaseIntentService;

/**
 * IntentService responsible for handling GCM messages.
 */
public class GCMIntentService extends GCMBaseIntentService {

	@SuppressWarnings("hiding")
	private static final String TAG = "GCMIntentService";
	public static final int DEFAULT_ALARM_REQUEST = 800;
	private SharedPreferences sharedPref;
	private SharedPreferences.Editor sharedEditor;

	public GCMIntentService() {
		super(SENDER_ID);
	}

	@Override
	protected void onRegistered(Context context, String registrationId) {
		Log.i(TAG, "Device registered: regId = " + registrationId);
		displayMessage(context, getString(R.string.gcm_registered));
		sharedPref = ((Activity) context).getPreferences(Context.MODE_PRIVATE);
		sharedEditor = sharedPref.edit();
		/* ServerUtilities.register(context, registrationId); */
	}

	@Override
	protected void onUnregistered(Context context, String registrationId) {
		Log.i(TAG, "Device unregistered");
		displayMessage(context, getString(R.string.gcm_unregistered));
		/*
		 * if (GCMRegistrar.isRegisteredOnServer(context)) {
		 * ServerUtilities.unregister(context, registrationId); } else { // This
		 * callback results from the call to unregister made on //
		 * ServerUtilities when the registration to the server failed.
		 * Log.i(TAG, "Ignoring unregister callback"); }
		 */
	}

	@Override
	protected void onMessage(Context context, Intent intent) {
		Log.i(TAG, "Received message");
		int i = Configuration.getArrayListAlarmDatas().size();
		int reqCode = DEFAULT_ALARM_REQUEST + i;

		Bundle b = intent.getExtras();

		AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		am.setTimeZone("GMT+09:00");
		Intent alarmIntent;
		PendingIntent pIntent;

		int kind = b.getInt("kind");
		GregorianCalendar calendar = new GregorianCalendar(
				TimeZone.getTimeZone("GMT+09:00"));

		String timeString = b.getString("time");
		int year = Integer.parseInt((String) timeString.subSequence(0, 4));
		int month = Integer.parseInt((String) timeString.subSequence(4, 6));
		int day = Integer.parseInt((String) timeString.subSequence(6, 8));
		int hour = Integer.parseInt((String) timeString.subSequence(8, 10));
		int minute = Integer.parseInt((String) timeString.subSequence(10, 12));

		Configuration.getArrayListAlarmDatas().add(
				new AlarmData(year, month, day, hour, minute, reqCode));
		Configuration.getArrayAdapterAlarmList().notifyDataSetChanged();

		sharedEditor.putInt("list" + i + "year", year);
		sharedEditor.putInt("list" + i + "month", month);
		sharedEditor.putInt("list" + i + "day", day);
		sharedEditor.putInt("list" + i + "hour", hour);
		sharedEditor.putInt("list" + i + "minute", minute);
		sharedEditor.putInt("list" + i + "reqCode", reqCode);
		sharedEditor.putInt("size", i);
		sharedEditor.commit();

		b.putInt("reqCode", reqCode);

		alarmIntent = new Intent(this, AlarmReceiver.class);
		alarmIntent.putExtras(b);
		pIntent = PendingIntent.getBroadcast(context, 0,	alarmIntent, 0);

		switch (kind) {
		case 1:
		case 2:
			calendar.set(year, month, day, hour, minute);
			am.setRepeating(AlarmManager.RTC_WAKEUP,
					calendar.getTimeInMillis(), 1000 * 60, pIntent);
			break;
		case 3:
		case 4:
		case 5:
		case 6:
			calendar.setTimeInMillis(System.currentTimeMillis());
			calendar.add(Calendar.SECOND, 0);
			am.set(AlarmManager.RTC, calendar.getTimeInMillis(), pIntent);
			break;
		}

		am.set(AlarmManager.RTC, calendar.getTimeInMillis(), pIntent);

		// notifies user
		generateNotification(context, b);
	}

	@Override
	protected void onDeletedMessages(Context context, int total) {
		Log.i(TAG, "Received deleted messages notification");
		String message = getString(R.string.gcm_deleted, total);
		displayMessage(context, message);
		Bundle b = new Bundle();
		b.putString("noticeTitle", message);
		// notifies user
		generateNotification(context, b);
	}

	@Override
	public void onError(Context context, String errorId) {
		Log.i(TAG, "Received error: " + errorId);
		displayMessage(context, getString(R.string.gcm_error, errorId));
	}

	@Override
	protected boolean onRecoverableError(Context context, String errorId) {
		// log message
		Log.i(TAG, "Received recoverable error: " + errorId);
		displayMessage(context,
				getString(R.string.gcm_recoverable_error, errorId));
		return super.onRecoverableError(context, errorId);
	}

	/**
	 * Issues a notification to inform the user that server has sent a message.
	 */
	private static void generateNotification(Context context, Bundle extras) {
		int icon = R.drawable.ic_stat_gcm;
		long when = System.currentTimeMillis();
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		String message = extras.getString("noticeTitle");
		Notification notification = new Notification(icon, message, when);

		String title = context.getString(R.string.app_name);
		Intent notificationIntent = new Intent(context, DemoActivity.class);
		// set intent so it does not start a new activity
		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent intent = PendingIntent.getActivity(context, 0,
				notificationIntent, 0);
		notification.setLatestEventInfo(context, title, message, intent);
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		notificationManager.notify(0, notification);
	}

}
